package test.springboot.config;

import redis.clients.jedis.Jedis;
import top.lingkang.finalsession.FinalSessionConfig;
import top.lingkang.finalsession.core.FinalRepository;
import top.lingkang.finalsession.jakarta.FinalSession;
import top.lingkang.finalsession.utils.SerializationUtils;

import java.io.IOException;

/**
 * 自定义redis存储session
 *
 * @author lingkang
 * Created by 2024/3/10
 */
public class FinalRepositoryRedis implements FinalRepository<FinalSession> {
    private Jedis jedis;

    @Override
    public void initConfig(FinalSessionConfig config) {
        // 使用jedis或者使用 spring提供的redisTemplate
        jedis = new Jedis("localhost", 6379);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> jedis.disconnect()));
    }

    @Override
    public FinalSession getSession(String id) {
        try {
            byte[] bytes = jedis.get(id.getBytes());
            if (bytes == null)
                return null;
            // 您也可以使用其他序列化工具
            return (FinalSession) SerializationUtils.unSerialization(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setSession(String id, FinalSession session) {
        try {
            // 您也可以使用其他序列化工具
            byte[] serialization = SerializationUtils.serialization(session);
            jedis.set(id.getBytes(), serialization);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteSession(String id) {
        jedis.del(id.getBytes());
    }

    @Override
    public void destroy() {
        jedis.disconnect();
    }
}
